package com.finance.activemq.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.activemq.configuration.ActivemqConfiguration;
import com.finance.logistics.anlyzier.DirectionHandler;
import com.finance.report.bean.pojo.LogisticsData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.camel.*;
import org.apache.camel.builder.DeadLetterChannelBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * 运单数据消息消费类
 * Created by CBWL on 2017/4/21.
 */
@Component
public class AcceptOrderConsumer {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private AcceptOrderConsumer(){
        this.logger.info("##############################AcceptOrderConsumer初始化######################################");
    }
    @Resource
    private DirectionHandler directionHandler;
    @Autowired
    private CamelContext camelContext;

    private  ObjectMapper om = new ObjectMapper();
    @Consume(uri = ActivemqConfiguration.QUEUE_ACCEPT_ORDER_ANALYZE,context = "camelContext")
    public void analyzeDirection(@Body String message) throws IOException {
        this.logger.info("消息消费：{}",message);
        LogisticsData logisticsData = null;
        logisticsData = this.om.readValue(message.getBytes("UTF-8"),LogisticsData.class);
        this.logger.info("[解析最初数据]LogisticData{}", net.sf.json.JSONObject.fromObject(logisticsData).toString());
        this.logger.info("[解析时间计算]字段解析开始{}",new Date().toString());
        this.directionHandler.doHandler(logisticsData);
    }
    @PostConstruct
    public void init(){
 //        this.camelContext.setHandleFault(true);
        try{
            this.camelContext.addRoutes(new RouteBuilder() {
                @Override
                public void configure() throws Exception {
            //        this.errorHandler(deadLetterChannel(ActivemqConfiguration.QUEUE_DEAD_QUEUE).maximumRedeliveries(2));
              //      this.from(ActivemqConfiguration.QUEUE_ACCEPT_ORDER_ANALYZE).to("bean:acceptOrderConsumer?method=analyzeDirection").routeId("routid_");
              //      this.from(ActivemqConfiguration.QUEUE_DEAD_QUEUE).to("bean:acceptOrderConsumer?method=handleError").routeId("deadrout_");
                }
            });
        }catch (Exception e){
            this.logger.error("JMS监听异常",e);
        }
    }
}
